package com.Maykk.Demo04;

import java.util.Map;
import java.util.Scanner;
import java.util.Set;

/**
 * @ClassName: ChatRoomMain
 * @Description: TODO 聊天室主方法 - 调用收发线程
 * @Author: MaykkStar@163.com
 */
public class ChatRoomMain {
    public static void main(String[] args) {
        Global.initUserMap();
        System.out.println(Global.userMap);
        System.out.println("= =============== =");
        System.out.println("  用户列表如下");
        System.out.println("= =============== =");
        Set<Integer> keySet = Global.userMap.keySet();
        // 来一个序号
        int index = 1;
        // 遍历输出用户
        for (Integer userKey : keySet) {
            System.out.println(index++ + " : " + Global.userMap.get(userKey));
        }

        // 选择登录用户

        do {
            login:
            System.out.println("请选择要登录的用户id：");
            index = new Scanner(System.in).nextInt();
        } while (index < 1 || index > Global.userMap.size());
        // 循环结束后会得到一个合法的用户id

        // 获取用户的端口号
        // int port = 0, i = 1;
        // for (Map.Entry<Integer, String> entry : Global.userMap.entrySet()) {
        //     if (index == i) {
        //         port = entry.getKey();
        //     }
        //     i++;
        // }
        int port = 20000 + index;

        // 获取用户名
        String userName = Global.userMap.get(port);

        // 创建发送和接收的线程
        Thread sendThread = new Thread(new SendThread(), userName);
        Thread receiveThread = new Thread(new ReceiveThread(port), userName);
        // 启动线程
        sendThread.start();
        receiveThread.start();

        // TODO 测试使用（删除）
        // System.out.println(port);
        // System.out.println("通过");
    }
}
